<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\UserCouponsLog as UserCouponsLogModel;
use app\common\model\CouponsOrder as CouponsOrderModel;
use app\common\model\UserCoupons as UserCouponsModel;
use think\Db;
use think\Exception;

class UserCoupons extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function lists(){
        $params = $this->request->param();
        $user_id = $this->auth->id;
        $user_coupons_log_model = new UserCouponsLogModel();
        $data = $user_coupons_log_model->with('coupons')->where([
            'user_id' => $user_id,
//            'type' => $params['type']
        ])->paginate(10);
        $this->success('success', $data);
    }

    public function order()
    {
        $params = $this->request->param();
        $user_id = $this->auth->id;
        $couponsOrderModel = new CouponsOrderModel();
        $data = $couponsOrderModel->order('id desc')->where([
            'user_id' => $user_id,
            'status' => 1
        ])->paginate(10);
        foreach ($data as $k => &$v) {
            $v['ext'] = json_decode($v['ext'],true);
        }
        $this->success('success', $data);
    }

    public function refund()
    {
        $params = $this->request->param();
        $user_id = $this->auth->id;

        Db::startTrans();
        try{
            $couponsOrderModel = new CouponsOrderModel();
            $data = $couponsOrderModel->where([
                'id' => $params['id'],
                'user_id' => $user_id,
            ])->find();
            $userCouponsModel = new UserCouponsModel();
            $nums = $userCouponsModel->where([
                'user_id' => $user_id,
            ])->value('nums');

            if($nums<$data['buy_num']){
                throw new \Exception("信息券已被使用，无法退款");
            }
            $data->status = -3;
            $data->refundtime = time();
            $data->save();

            $after['order'] = $data;
            $after['type'] = 'coupons';
            \think\Hook::listen('xykeep_order_refund_after', $after);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('success', $data);
    }
}